package com.efounder.zone.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.activity.ViewPagerActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.widget.RoundImageView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.ResStringUtil;
import com.efounder.zone.R;
import com.efounder.zone.bean.TalksBean;
import com.efounder.zone.commentview.DetailCommentListView;
import com.efounder.zone.commentview.ZoneCommentBean;
import com.efounder.zone.event.MobileZoneDetailBackEvent;
import com.efounder.zone.event.MobileZoneRefreshEvent;
import com.efounder.zone.util.CommentUtil;
import com.efounder.zone.util.ZoneRequestUtil;
import com.efounder.zone.util.ZoneTimeUtil;
import com.efounder.zone.widget.LikeTextView;
import com.efounder.zone.widget.MutiContentDisplayView;
import com.efounder.zone.widget.StatusAlert;
import com.efounder.zone.widget.ThumbsCommentsTransmitView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Random;

import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.zone.util.ZoneHelperUtil.gotoOtherZone;

/**
 * 详情界面
 */

public class MobileZoneDetailActivity extends BaseActivity implements BGANinePhotoLayout.Delegate {

    private int position;
    private ImageView mIvBack;

    RoundImageView ivAvatar;
    TextView tvName;
    TextView tvTime;
    LikeTextView likeTextView;
    TextView tvDeviceType;
    MutiContentDisplayView mutiContentDisplayView;
    DetailCommentListView mCommentListView;
    LinearLayout llComment;
    ThumbsCommentsTransmitView thumbsCommentsTransmitView;
    private TalksBean talkBean;
    private int id;
    private TalksBean talkBeanCopy;
    private ScrollView scrollView;
    private TextView mTvScore;
    private ImageView mIvScoreIcon;
    private TalksBean talkBeanFromIntent;
    /**
     * 是否显示银钻积分
     */
    private boolean isShowIntegral;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mobile_zone_detail);
        EventBus.getDefault().register(this);
        LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.common_text_please_wait));
//        CommentUtil.cancelCommentInput();
        Intent intent = getIntent();
        position = intent.getIntExtra("position", -1);
        id = intent.getIntExtra("id", -1);
        isShowIntegral = EnvSupportManager.isSupportShowIntergral();
        initView();

        //判断talksBean,如果为null，表示原说说已经删除，使用上个页面传过来的talksbean，不能使用接口请求的talksbean
        //因为如果原说说已经删除，使用接口请求下来的talksbean为null（接口有问题）
        talkBeanFromIntent = (TalksBean) intent.getSerializableExtra("talkBean");
        if (talkBeanFromIntent != null && talkBeanFromIntent.getObj().getPostContent() == null) {
            talkBean = talkBeanFromIntent;
            //todo 浏览次数修改
            int count = talkBean.getObj().getReadCount()
                    * ThumbsCommentsTransmitView.MULTI + new Random().nextInt(99);
            talkBean.getObj().setReadCount(count);
            loadData();
            LoadingDataUtilBlack.dismiss();
            scrollView.setVisibility(View.VISIBLE);
        } else {
            initData();
        }
    }

    public static void start(Context context, int id) {
        Intent starter = new Intent(context, MobileZoneDetailActivity.class);
        starter.putExtra("id", id);
        context.startActivity(starter);
    }

    /**
     * 请求详情数据
     */
    private void initData() {
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
        params.put("password", EnvironmentVariable.getProperty(CHAT_PASSWORD));
        ZoneRequestUtil.getCommonRequest(TAG, "shortposts/" + id + "/p", params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    JSONObject object = new JSONObject(response);
                    if (object.has("status") && object.optString("status").equals("001003")) {
                        //short-post does not exist when get!
                        ToastUtils.showShort(R.string.zone_dynamic_none_or_delete);
                        finish();
                        return;
                    }
                    scrollView.setVisibility(View.VISIBLE);
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    //todo 好麻烦。。。。
                    int count = 0;
                    if (talkBeanFromIntent != null) {
                        count = talkBeanFromIntent.getObj().getReadCount();
                    }

                    talkBean = gson.fromJson(response, TalksBean.class);
                    if (null != talkBean) {
                        if (count != 0) {
                            talkBean.getObj().setReadCount(count);
                        } else {
                            //todo 浏览次数修改 intent 没有值，需要设置
                            count = talkBean.getObj().getReadCount()
                                    * ThumbsCommentsTransmitView.MULTI + new Random().nextInt(99);
                            talkBean.getObj().setReadCount(count);
                        }
                        loadData();
                    }

                } catch (Exception e) {
                    scrollView.setVisibility(View.GONE);
                    StatusAlert.failAlert(MobileZoneDetailActivity.this, LayoutInflater.from(MobileZoneDetailActivity.this)
                            .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_fail_to_parse_data));
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
                scrollView.setVisibility(View.GONE);
                StatusAlert.failAlert(MobileZoneDetailActivity.this, LayoutInflater.from(MobileZoneDetailActivity.this)
                        .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_fail_to_req_data));
                LoadingDataUtilBlack.dismiss();
            }
        });

    }

    /**
     * 加载数据
     */

    private void loadData() {
        try {
            //昵称
            int userId = talkBean.getObj().getPostAuthor();
            User user = WeChatDBManager.getInstance().getOneUserById(userId);

            String authorUserName = talkBean.getObj().getAuthorUserName();
            String authorAvatar = talkBean.getObj().getAuthorAvatar();
            if (authorUserName == null) {
                authorUserName = user.getNickName();
            }
            if (authorAvatar == null || "".equals(authorAvatar)) {
                authorAvatar = user.getAvatar();
            }
            tvName.setText(authorUserName);
            //时间
            if (talkBean.getObj().getPostCreatetime() != null)
                tvTime.setText(ZoneTimeUtil.formatTime(talkBean.getObj().getPostCreatetime()));
            LXGlideImageLoader.getInstance().showUserAvatar(this, ivAvatar, authorAvatar);
            mutiContentDisplayView.setDelegate(this);
            //设备
            tvDeviceType.setText(talkBean.getObj().getDevice());
            //积分
            //显示积分
            String integral = "+" + talkBean.getObj().getIntegral() + ResStringUtil.getString(R.string.zone_silver_drill);
            mTvScore.setText(integral);
            //浏览次数、点赞、评论和分享View(不能在这里设置浏览数据)
            thumbsCommentsTransmitView.display(position, talkBean, getSupportFragmentManager());
            //点赞
            likeTextView.setLikeBeanList(talkBean.getLikes());
            likeTextView.setListener(new LikeTextView.onItemClickListener() {
                @Override
                public void onItemClick(TalksBean.LikesBean bean) {
                    gotoOtherZone(MobileZoneDetailActivity.this, bean.getUserId());
                }
            });
            //评论
            mCommentListView.setCommentData(talkBean.getComment());
            mCommentListView.setDetailCommentItemListener(new DetailCommentListView.OnDetailCommentItemListener() {
                @Override
                public void onNameClick(String userId) {
                    gotoOtherZone(MobileZoneDetailActivity.this, Integer.valueOf(userId));
                }

                @Override
                public void onCommentClick(final ZoneCommentBean commentBean) {
                    if (commentBean.getCommentUserId() == Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))) {
                        //自己的评论，点击删除
                        new AlertDialog.Builder(MobileZoneDetailActivity.this).setMessage(ResStringUtil.getString(R.string.zone_confirm_delete)).setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //删除评论
                                CommentUtil.deleteComment(MobileZoneDetailActivity.this, position, talkBean, commentBean.getId());
                            }
                        }).setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).show();
                    } else {
                        //回复其他人的评论
                        CommentUtil.sendComment(MobileZoneDetailActivity.this, position, commentBean, talkBean, getSupportFragmentManager());
                    }
                }
            });
            //判断content是否为null
            if (talkBean.getObj().getPostContent() != null) {
                //文字、图片或视频
                mutiContentDisplayView.display(talkBean.getObj());
            } else {
                //原说说被删除
                mutiContentDisplayView.sourceContentDeleteStyle((String) talkBean.getObj().getTransmitContent());
            }

            //点击评论框评论
            llComment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    sendComment(position, null);
                    CommentUtil.sendComment(MobileZoneDetailActivity.this, position, null, talkBean, getSupportFragmentManager());

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initView() {
        mIvBack = (ImageView) findViewById(R.id.iv_back);
        ivAvatar = (RoundImageView) findViewById(R.id.mobile_zone_detail_avatar);
        tvName = (TextView) findViewById(R.id.mobile_zone_detail_nickname);
        tvTime = (TextView) findViewById(R.id.mobile_zone_detail_time);
        mutiContentDisplayView = (MutiContentDisplayView) findViewById(R.id.mobile_zone_detail_muticontent_display_view);
        likeTextView = (LikeTextView) findViewById(R.id.mobile_zone_detail_likeview);
        tvDeviceType = (TextView) findViewById(R.id.mobile_zone_detail_device_type);
        thumbsCommentsTransmitView = (ThumbsCommentsTransmitView) findViewById(R.id.mobile_zone_detail_thumbs_comments_container);
        llComment = (LinearLayout) findViewById(R.id.mobile_zone_detail_ll_comment);
        mCommentListView = (DetailCommentListView) findViewById(R.id.mobile_zone_detail_ctv_comment_list);
        scrollView = (ScrollView) findViewById(R.id.mobile_zone_detail_container);
        mTvScore = (TextView) findViewById(R.id.mobile_zone_tv_jifen);
        mIvScoreIcon = (ImageView) findViewById(R.id.mobile_zone_icon_jifen);
        scrollView.setVisibility(View.GONE);
        TextView title = (TextView) findViewById(R.id.tv_title);
        title.setText(ResStringUtil.getString(R.string.zone_detail));
        Drawable drawable = mIvScoreIcon.getDrawable();
        if (drawable != null && drawable instanceof AnimationDrawable) {
            ((AnimationDrawable) drawable).start();
        }
        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //控制积分布局的显示
        if(isShowIntegral){
            mIvScoreIcon.setVisibility(View.VISIBLE);
            mTvScore.setVisibility(View.VISIBLE);
        }else {
            mIvScoreIcon.setVisibility(View.GONE);
            mTvScore.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {

        String[] strings = models.toArray(new String[0]);
        ViewPagerActivity.showImageWall(MobileZoneDetailActivity.this, strings, position, view);
    }

    /**
     * 刷新页面
     *
     * @param
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshEvent(MobileZoneRefreshEvent mobileZoneRefreshEvent) {
        talkBeanCopy = talkBean;
        talkBean = mobileZoneRefreshEvent.getTalksBean();
        String status = mobileZoneRefreshEvent.getmStatus();
        //如果是转发，转发成功后postion应该加1
        if ("transmit".equals(status)) {
            this.position = position + 1;
            StatusAlert.successAlert(this, LayoutInflater.from(this)
                    .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_forward_success));
            //转发后，talkbean不能改变
            talkBean = talkBeanCopy;
        }
        //加载数据
        loadData();
        int userId = talkBean.getObj().getPostAuthor();
        User user = WeChatDBManager.getInstance().getOneUserById(userId);

        try {
            JSONObject postContent = new JSONObject(talkBean.getObj().getPostContent());
            Object transmitContent = talkBean.getObj().getTransmitContent();
            Object transmitSourceUserid = talkBean.getObj().getTransmitSourceUserid();
            //查询取出用户名
            String userName = "";
            if (null != transmitSourceUserid) {
                if (talkBean.getObj().getTransmitSourceUsername() != null && !"".equals(talkBean.getObj().getTransmitSourceUsername())) {
                    userName = (String) talkBean.getObj().getTransmitSourceUsername();
                } else {
                    User postUser = WeChatDBManager.getInstance().getOneUserById(Integer.parseInt(transmitSourceUserid.toString()));
                    userName = postUser.getNickName();
                }

            }
            String text = postContent.optString("text");
            //转发item
            if (null != transmitContent && null != transmitSourceUserid) {
                mutiContentDisplayView.transmitStyle(Integer.valueOf((String) transmitSourceUserid), transmitContent, text, userName);
            } else {
                //正常item
                mutiContentDisplayView.ownStyle(user.getNickName(), postContent.getInt("type"));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void finish() {
//        CommentUtil.cancelCommentInput();
        //防止闪退
        if (null != talkBean)
            EventBus.getDefault().post(new MobileZoneDetailBackEvent(talkBean, position));
        EventBus.getDefault().unregister(this);
        LoadingDataUtilBlack.dismiss();
        super.finish();
    }

    @Override
    protected void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }
}
